package com.wyd.rabbitmq.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 雷哥
 * @Date: 2020/10/09/0:08
 * @Description:
 */
@Component
public class WatchMessageImpl implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnCallback {

  @Autowired
  private RabbitTemplate rabbitTemplate;


  @PostConstruct
  public void initRabbitTemplate(){
    rabbitTemplate.setConfirmCallback(this);
    rabbitTemplate.setReturnCallback(this);
  }

  /**
   * 当消息到达交换机之后该方法会被回调
   * @param correlationData  相关的数据
   * @param ack  交换机接收消息是否成功
   * @param cause  如果没有成功，返回原因
   */
  @Override
  public void confirm(CorrelationData correlationData, boolean ack, String cause) {
    if(ack){
      System.out.println("交换机接收消息成功");
    }else{
      System.out.println("correlationData:"+ correlationData.getId());
      System.out.println("交换机接收消息失败：原因:"+cause);
    }
  }

  /**
   * 消息如未正常到达队列里面会回调
   * @param message  消息内容
   * @param replyCode  回调的响应码
   * @param replyText  响应文本
   * @param exchange 交换机
   * @param routingKey  路由key
   */
  @Override
  public void returnedMessage(Message message, int replyCode, String replyText, String exchange,
      String routingKey) {
    System.out.println(message.getMessageProperties().getDeliveryTag());
    System.out.println(new String(message.getBody()));
    System.out.println("消息未正常到达队列-replyCode:"+replyCode);
    System.out.println("消息未正常到达队列-replyText:"+replyText);
    System.out.println("消息未正常到达队列-exchange:"+exchange);
    System.out.println("消息未正常到达队列-routingKey:"+routingKey);
  }
}
